<?php
/**
 * News Abstraction
 * 
 * @author MF
 * @version 2.1
 */

class News extends A_Content  {
	
	/**
	 * Возвращаяет запись с новостью по Id
	 *
	 * @param Integer $id
	 * @return SingleNews
	 */
	public function getById($id) {
		if (!isset($this->_cashe_obj[$id])) {
			$this->_cashe_obj[$id] = new SingleNews($this->_top,$this,$id);
		}
		
		return $this->_cashe_obj[$id];
	}
	
	public function add() {
		$this->_top->_sql->exeDummy("INSERT INTO {$this->_top->_sql->tab_pref}news(add_date) VALUES(NOW());");
		$id = $this->_top->_sql->last_insert_id();
		return $this->getById($id);
	}
	
}

class SingleNews extends A_SingleContent {
	
	public $config;
	
	public function loader()
	{
		unset($this->config);
		
		$get_data = $this->_top->_sql->exe("SELECT * FROM {$this->_top->_sql->tab_pref}news c WHERE news_id={$this->_content_id}");
		if (count($get_data)==0)
			return false;
		else {
			$this->_data = $get_data[0];
		}
		return true;
	}
	
	public function __get($param) {
		if ($param=='config') {
			return $this->_top->Utils->json_decoder($this->json_config);
		} elseif (isset($this->_data[$param])) {
			return $this->_data[$param];
		} else {
			throw $this->_top->Utils->PushError('Geting Undefinded News object property','Системная ошибка. Обратитесь к разработчикам');
		}
	}
	
	public function __set($param,$value) {
		if ($param=='add_date' || $param=='news_id') {
			return false;
		} elseif (isset($this->_data[$param])) {
			$this->_data[$param] = $value;
			$ins_value = $this->_top->Utils->prepareValueForSQL($value);
			$this->_top->_sql->exeDummy("UPDATE {$this->_top->_sql->tab_pref}news SET `$param`='$ins_value',last_mod=NOW() WHERE news_id={$this->_content_id}");
		} else {
			throw $this->_top->Utils->PushError('Seting Undefinded News object property','Системная ошибка. Обратитесь к разработчикам');
		}
	}
	
	public function length() {
		$get_data = $this->_top->_sql->exe("SELECT count(*) as c FROM {$this->_top->_sql->tab_pref}news_note c WHERE news_id={$this->_content_id}");
		return $get_data[0]['c'];
	}
	
	
	public function add() {
		$cfg = $this->config;
		$fields = '';
		$values = '';
		for ($c=0;$c<count($cfg);$c++) {
			$fields .= ",`{$cfg[$c][1]}`";
			$values .= ",'{$this->_top->Content($cfg[$c][2])->add()->_content_id}'";
		}
		$this->_top->_sql->exeDummy("INSERT INTO {$this->_top->_sql->tab_pref}news_note(add_date,news_id$fields) VALUES(NOW(),{$this->_content_id}{$values});");
		$id = $this->_top->_sql->last_insert_id();
		return $this->_top->NewsNote->getById($id);
	}
	
	
	public function deleter() {
		$notes_list = $this->_top->_sql->exe("SELECT news_note_id as c FROM {$this->_top->_sql->tab_pref}news_note c WHERE news_id={$this->_content_id}");
		for ($n=0;$n<count($notes_list);$n++) {
			$this->_top->NewsNote->getById($notes_list[$n]['c'])->delete();
		}
		$this->_top->_sql->exeDummy("DELETE FROM {$this->_top->_sql->tab_pref}news WHERE news_id={$this->_content_id}");
	}
	
	/**
	 * Enter description here...
	 *
	 * @param Integer $idx
	 * @return SingleNewsNote
	 */
	public function getById($idx) {
		return $this->_top->NewsNote->getById($idx);
	}
	
	
	/**
	 * Returns new instance of NewsFilter class
	 *
	 * @return NewsFilter
	 */
	public function filter() {
		return new NewsFilter($this->_top,$this->_content_id);
	}
	
	
}


class NewsFilter   {
	/**
	 * Link to Root object
	 *
	 * @var MF_Main
	 */
	private $_top;
	private $_news_id;
	private $_condition_list = array();
	private $_limits = null;
	private $_results = null;
	private $_total_amount = null;
	
	function __construct($top,$news_id) {
		$this->_top  = $top;
		$this->_news_id = $news_id;
	}
	
	/**
	 * Adding date "from to" in the condition
	 *
	 * @param String $date - Date time in MySql format
	 * @return NewsFilter
	 */
	public function dateFromTo($from,$to) {
		// TODO - need to make validation here
		array_push($this->_condition_list,"`add_date` BETWEEN '{$from} 00:00:00' AND '{$to} 23:59:59'");
		return $this;
	}
	
	/**
	 * Inserts condition where is to search only published or not published news 
	 *
	 * @param Integer $value - avalible values 0 or 1
	 * @return NewsFilter
	 */
	public function publishFlag($value) {
		// TODO - need to make validation here
		array_push($this->_condition_list,"publish_f='$value'");
		return $this;
	}
	
	/**
	 * Sets amount of searched news
	 *
	 * @param Integer $from_row
	 * @param Integer $amount
	 * @return NewsFilter
	 */
	public function setLimits($from_row,$amount) {
		// TODO - need to make validation here
		$this->_limits = array($from_row,$amount);
		return $this;
	}
	
	/**
	 * Runs searching filtering news process
	 *
	 * @return NewsFilter
	 */
	public function Make() {
		$get_amount = $this->_top->_sql->exe("SELECT count(*) as c FROM {$this->_top->_sql->tab_pref}news_note c WHERE news_id={$this->_news_id} AND "
			.(count($this->_condition_list)>0 ? implode(' AND ',$this->_condition_list) : '1'));
		$this->_total_amount = $get_amount[0]['c'];
		
		$get_result = $this->_top->_sql->exe("SELECT news_note_id FROM {$this->_top->_sql->tab_pref}news_note c WHERE news_id={$this->_news_id} AND "
			.(count($this->_condition_list)>0 ? implode(' AND ',$this->_condition_list) : '1')
			.' ORDER BY `add_date` DESC'
			.($this->_limits!==null ? " LIMIT {$this->_limits[0]},{$this->_limits[1]}" : ''));
		$this->_results = array();
		for ($r=0;$r<count($get_result);$r++) {
			array_push($this->_results,$get_result[$r]['news_note_id']); 
		}
		
		return $this;
	}
	
	public function length() {
		if ($this->_results===null) {
			$this->Make();
		}
		return count($this->_results); 
	}
	
	public function total_length() {
		return $this->_total_amount;
	}
	
	public function item($idx) {
		if ($this->_results===null) {
			$this->Make();
		}
		return $this->_top->NewsNote->getById($this->_results[$idx]);
	}
	
}
?>
